import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:path_provider/path_provider.dart';
// import 'package:package_info_plus/package_info_plus.dart';

import 'package:shared_preferences/shared_preferences.dart';
import 'package:syn_4s/core/extension/build_context_extension.dart';
import 'package:syn_4s/core/model/version_model.dart';
import 'package:syn_4s/core/services/config.dart';
import 'package:syn_4s/core/utils/location_per_utils.dart';
import 'package:syn_4s/core/utils/toast_utils.dart';

import '../../ui/pages/login/login.dart';
import '../../ui/widgets/check_update_dialog.dart';
import '../constants/sp_key.dart';
import '../services/setting_request.dart';
import '../utils/dialog_utils.dart';

class SettingViewModel {
  var language = "".obs;
  var version = "1.0.0".obs;
  var versionModel = VersionModel().obs;
  int? languageId;

  init() {
    SharedPreferences.getInstance().then((value) {
      languageId = value.getInt(keyLanguage) ?? 1;
      setLanguageValue();
    });
    // PackageInfo.fromPlatform().then((value){
    //   PackageInfo info = value;
    //   version.value = "V${info.version}";
    // });
  }

  setLanguageValue() {
    language.value = languageId == 1 ? "中文" : "English";
  }

  logout(BuildContext context) {
    DialogUtils.loading(context);
    SettingRequest.logOut().then((value) {
      clearSPAndLogOut(context);
    }).catchError((err) {
      clearSPAndLogOut(context);
    });
  }

  clearSPAndLogOut(BuildContext context) {
    SharedPreferences.getInstance().then((value) {
      // NotificationUtil().cancelAll();
      value.setString(keyToken, "");
      value.setString(keyRefreshToken, "");
      value.setString(keyProjName, "");
      value.setString(keyUserId, "");
      value.setString(keyProjId, "");
      DialogUtils.closeDialog(context);
      Get.offAllNamed(LoginScreen.routeName);
    });
  }

  getAndroidVersion(BuildContext context) {
    checkWritePermission().then((isGranted){
      if(isGranted) {
        SettingRequest.getVersion().then((versionInfo) {
          if (versionInfo.status != HttpConfig.success) {
            return;
          }
          if (versionInfo.data == null) {
            ToastUtils.showToast(context.l10n.current_version);
            return;
          }
          var newVersion = versionInfo!.data!.versionNumber!
              .replaceAll(".", "")
              .replaceAll("V", "");
          var oldVersion = version.replaceAll(".", "");
          if (int.parse(newVersion) > int.parse(oldVersion)) {
            versionModel.value = versionInfo!.data!;
            showCheckUpdateDialog(context);
          } else {
            ToastUtils.showToast(context.l10n.current_version);
          }
        });
      } else {
        ToastUtils.showToast(context.l10n.write_permission);
      }
    });
  }

  ///检查更新
  showCheckUpdateDialog(BuildContext context) {
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) => CheckUpdateDialog(),
    );
  }
  
  downloadApk(){
    getTemporaryDirectory().then((cacheDir){
      File file = File('${cacheDir.path}/${versionModel.value.path}');
      if (file.existsSync()) {
        file.delete();
      }
      SettingRequest.downloadFile(versionModel!.value!.path!, file, (count, total){
        print("===============================================计数$count");
        print("===============================================总数$total");
      }).then((result){
        installApk(result.path);
      });
    });
  }

  Future<bool> installApk(String apkPath) async {
    try {
      final bool success = await MethodChannel('apk_installer').invokeMethod(
          'installApk', apkPath);
      return success;
    } on PlatformException catch (e) {
      print("Failed to install APK: '${e.message}'.");
      ToastUtils.showToast(e.message.toString());
      return false;
    }
  }

}
